/**
 * @Author: hrg
 * @Date: 2023-12-13 09:57:49
 * @LastEditTime: 2023-12-13 19:17:54
 * @FilePath: \web\src\api\http.js
 * @Description: 
 */
import axios from "axios";
import { notification, message as Msg } from "ant-design-vue";

import {userCounterStore} from '@/store/module/user'
// import { setStorage, StorageName, getStorage } from "@/core/tools/storage.js";




const refreshToken = (response) => {
  let token = response.headers.authorization;
  if (token) {
    localStorage.setItem("USER_TOKEN",token)
  }
};

notification.config({
  duration: 5
});

export const baseurl = () => {
  return "http://127.0.0.1:8023/"
  // if (getStorage(StorageName.serverIndex) == null) {
  //   setStorage(StorageName.serverIndex, 0);
  // }
  // if (window.configs.servers[getStorage(StorageName.serverIndex)]) {
  //   return window.configs.servers[getStorage(StorageName.serverIndex)]["api"];
  // } else {
  //   notification.error({
  //     message: "config error",
  //     description: "config error"
  //   });
  //   return "";
  // }
};

class Http {
  constructor(config) {
    this.config = config || {
      timeout: 1000 * 60 * 3, //默认三分钟
      withCredentials: true,
      baseURL: baseurl(),
      headers: {
        "Content-Type": "application/json; charset=utf-8"
      }
    };
  }

  interceptors(instance) {

    //请求拦截器
    instance.interceptors.request.use(
      (config) => {
        const userCounter = userCounterStore()
        const token = userCounter.token
        if (token) {
          config.headers["Authorization"] = token;
        }

        // config.cancelToken = new axios.CancelToken(async (cancel) => {
        //   await store.dispatch("app/execCancelToken", { cancelToken: cancel });
        // });
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );
    
    // 响应拦截 
    instance.interceptors.response.use(
      (response) => {
        console.log("响应拦截器传递的参数：",response)
        refreshToken(response); //有token 就刷新
        if (response.data.code > 1) {
          notification.error({
            message: response.data.code,
            description: response.data.msg
          });
        }
        return response.data;
      },
      (error) => {
        console.log("响应拦截器：error", error);
        if (error.response) {
          refreshToken(error.response); //有token 就刷新
          if (error.response.status === 403) {
            notification.error({
              message: "权限不足",
              description: error.response.request.responseURL
            });
          } else if (error.response.status === 401) {
            // store.dispatch("user/logout").then(() => {
            //   // setTimeout(() => {
            //   //   window.location.reload();
            //   // }, 2000);
            // });
          } else if (error.response.status === 404) {
            notification.error({
              message: "找不到接口",
              description: "找不到接口"
            });
          }
        } else {
          let { message } = error;
          Msg.error(message);
        }
        return Promise.reject("error response");
      }
    );
  }

  request(options) {
    if (window.__TAURI_IPC__) {
      this.config.baseURL = baseurl();
    }
    const instance = axios.create();
    const requestOptions = Object.assign({}, this.config, options);
    this.interceptors(instance);
    return instance(requestOptions);
  }
}

const http = new Http();
export default http;
